Skip to content

fix(credits): meter LLM credits when a turn fails after a side-effect - #786

Open
sweetmantech wants to merge 1 commit into
mainfrom
fix/meter-credits-on-failed-turn
Open

fix(credits): meter LLM credits when a turn fails after a side-effect#786
sweetmantech wants to merge 1 commit into
mainfrom
fix/meter-credits-on-failed-turn

Conversation

@sweetmantech

@sweetmantech sweetmantech commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Tracked by chat#1885 (billing-integrity row; sibling to api#782/#783 — recommend splitting into a dedicated billing-integrity tracker).

Problem

runAgentWorkflow charged the account + wrote the usage_events audit row only at app/lib/workflows/runAgentWorkflow.ts L119, gated on if (result.responseMessage) after runAgentStep returned — inside a try whose only companion is a finally (no catch).

The customer email is a send_email tool call executed inside runAgentStep (mid-turn). So a turn that emails the customer and then throws — or returns without a responseMessage — skips billing entirely: email out, wallet not debited, no usage_events row.

getCreditUsage/handleChatCredits can't be the cause: an unknown/zero-priced model still writes a ≥1¢ row with model_id (Math.max(1, …)). Zero rows ⇒ handleChatCredits was never called.

Evidence (2026-07-23)

A scheduled briefing for account fade8fd2-… on the new moonshotai/kimi-k3 default emailed "Brauxelion Weekly" at 20:54 but wrote 0 usage_events rows with a model_id. The earlier anthropic/claude-sonnet-5 run wrote 1 (106¢, 2.63M in / 31.8k out). Both runs' model-independent scrape/tool charges (235¢, model_id=null) were identical — only the LLM line vanished. With Kimi now the default for every headless briefing, this risks systemic email-but-not-bill with no audit trail.

Fix

Extract the charge into an idempotent chargeTurn() and call it (a) on the normal path and (b) as a finally backstop. A turn that produced a customer-facing side-effect now always lands a wallet debit + audit row; ZERO_USAGE with no gateway cost floors to the 1¢ minimum, so a failed turn still writes a model_id row. chargeTurn guards on a charged flag so the normal + user-abort paths bill exactly once. The original error still propagates after the backstop runs.

Behavior

Turn outcome Before After
Normal finish (responseMessage) 1 charge (real usage) 1 charge (real usage) — unchanged
User-abort (responseMessage) 1 charge 1 charge — unchanged
Returns no responseMessage 0 charges 1 charge (1¢ floor + model_id row) ✅
Throws after send_email fired 0 charges 1 charge (1¢ floor + model_id row) ✅; error still propagates

Tests

TDD red→green. Flipped the two tests that codified the gap ("does NOT bill when no responseMessage" / "…when it throws") to assert the turn is now billed with the 1¢ floor.

  • pnpm exec vitest run app/lib/workflows/__tests__/runAgentWorkflow.test.ts20 passed
  • pnpm exec vitest run app/lib/workflows lib/credits129 passed
  • pnpm exec eslint on both changed files → clean

No API contract change → no docs PR (a billing side-effect, like api#782). Note: tsc --noEmit has 203 pre-existing errors on main (trigger/tasks test fixtures); this PR adds none, and runAgentWorkflow.ts is type-clean.

Follow-up (out of scope)

Confirm why Kimi returned no responseMessage in this workflow (Vercel workflow run logs: finishReason / thrown error) — that's a model-integration question separate from this billing-integrity fix.

🤖 Generated with Claude Code


Summary by cubic

Ensures LLM credits are charged when a turn fails or returns no response after a side-effect, preventing email-but-not-billed gaps. Billing now always records a usage_events row with a 1¢ floor.

  • Bug Fixes
    • Added idempotent chargeTurn() and invoke it on success and in finally.
    • Bills user-stop and failure paths; uses ZERO_USAGE → 1¢ minimum; writes a model_id row.
    • Guards to charge exactly once; original errors still propagate.
    • Updated tests to assert billing on no-response and thrown-turn cases; no API changes.

Written for commit 007840d. Summary will update on new commits.

Review in cubic

runAgentWorkflow charged the account + wrote the usage_events audit row
only on `if (result.responseMessage)` after runAgentStep returned. The
customer email is a `send_email` tool call executed INSIDE runAgentStep,
so a turn that emailed the customer and then threw (or returned no
responseMessage) hit the try's `finally` with no catch and skipped
billing entirely: email out, wallet not debited, no usage_events row.

Observed 2026-07-23: a scheduled briefing on moonshotai/kimi-k3 emailed
the customer at 20:54 but wrote 0 rows with a model_id (vs the sonnet-5
run's 1). Both runs' model-independent scrape/tool charges were
identical; only the LLM line went missing.

Fix: extract the charge into an idempotent `chargeTurn` and call it both
on the normal path and as a `finally` backstop. A turn that produced a
customer-facing side-effect now always lands a wallet debit + audit row;
ZERO_USAGE with no gateway cost floors to the 1c minimum, so a failed
turn still writes a model_id row. Normal + user-abort paths bill exactly
once (chargeTurn guards on `charged`); the original error still
propagates after the backstop runs.

Flips two tests that codified the gap ("does NOT bill when no
responseMessage" / "...when it throws") to assert the turn is now billed.
20 workflow tests + 129 workflows/credits domain tests pass; eslint clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@cursor

cursor Bot commented Jul 23, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@vercel

vercel Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
api Ready Ready Preview Jul 23, 2026 9:23pm

Request Review

@coderabbitai

coderabbitai Bot commented Jul 23, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@sweetmantech, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 6 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: e6a36048-1b6f-4cb8-89a0-e3df854d1839

📥 Commits

Reviewing files that changed from the base of the PR and between ce2357e and 007840d.

⛔ Files ignored due to path filters (1)
  • app/lib/workflows/__tests__/runAgentWorkflow.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by app/**
📒 Files selected for processing (1)
  • app/lib/workflows/runAgentWorkflow.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/meter-credits-on-failed-turn

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 2 files

Confidence score: 3/5

  • In app/lib/workflows/runAgentWorkflow.ts, the workflow can mark a turn as completed before credit debit is confirmed, and handleChatCredits currently swallows failures, so transient billing errors may leave side-effecting turns unbilled with no retry signal. Have handleChatCredits return/propagate a success result and only set the completion flag after a confirmed debit (or trigger a compensating/retry path).
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="app/lib/workflows/runAgentWorkflow.ts">

<violation number="1" location="app/lib/workflows/runAgentWorkflow.ts:118">
P2: A transient credit-recording failure still leaves a side-effecting turn unbilled: this flag is set before the debit outcome is known, while `handleChatCredits` swallows failures. Return/propagate a success result and mark the turn charged only after a successful debit, so the finally path can retry a failed normal-path attempt.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant Workflow as runAgentWorkflow
    participant AgentStep as runAgentStep
    participant Billing as chargeTurn (NEW)
    participant Credits as handleChatCredits
    participant DB as Database
    participant Email as send_email Tool

    Note over Workflow,Email: Turn execution — agent may call tools (e.g. send_email) mid-step

    Workflow->>AgentStep: Execute step with assistantMessageId
    AgentStep->>Email: Customer-facing tool call (side-effect)

    alt Normal path: AgentStep returns responseMessage
        AgentStep-->>Workflow: result with responseMessage.metadata
        Workflow->>Billing: chargeTurn() — idempotent
        Billing->>Credits: handleChatCredits(usage=real)
        Credits->>DB: deduct_credits_with_audit (wallet + usage_events)
        DB-->>Credits: OK
        Credits-->>Billing: done
        Billing-->>Workflow: charged=true
        Workflow->>Workflow: Auto-commit + push (if natural finish)

    else AgentStep returns without responseMessage (no message, but email may have fired)
        AgentStep-->>Workflow: result, responseMessage=undefined
        Workflow->>Billing: chargeTurn() — idempotent
        Billing->>Credits: handleChatCredits(usage=ZERO_USAGE → 1¢ floor)
        Credits->>DB: deduct_credits_with_audit (model_id row, 1¢ min)
        DB-->>Credits: OK
        Credits-->>Billing: done
        Billing-->>Workflow: charged=true

    else AgentStep throws after email sent
        AgentStep-->>Workflow: Error thrown
        Workflow->>Billing: chargeTurn() — idempotent (in finally)
        Billing->>Credits: handleChatCredits(usage=ZERO_USAGE → 1¢ floor)
        Credits->>DB: deduct_credits_with_audit (model_id row, 1¢ min)
        DB-->>Credits: OK
        Credits-->>Billing: done
        Billing-->>Workflow: charged=true
        Workflow->>Workflow: Error propagates
    end

    Note over Workflow: Finally block — always runs

    Workflow->>Billing: chargeTurn() — idempotent guard (already charged, no-op)
    Billing-->>Workflow: skipped (charged=true)

    Workflow->>Workflow: cleanup: clearChatActiveStream + commitChatTurn (parallel)

    alt Error path (if AgentStep threw)
        Workflow-->>Workflow: Error still propagates after billing + cleanup
    end
Loading

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

let charged = false;
const chargeTurn = async () => {
if (charged) return;
charged = true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: A transient credit-recording failure still leaves a side-effecting turn unbilled: this flag is set before the debit outcome is known, while handleChatCredits swallows failures. Return/propagate a success result and mark the turn charged only after a successful debit, so the finally path can retry a failed normal-path attempt.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At app/lib/workflows/runAgentWorkflow.ts, line 118:

<comment>A transient credit-recording failure still leaves a side-effecting turn unbilled: this flag is set before the debit outcome is known, while `handleChatCredits` swallows failures. Return/propagate a success result and mark the turn charged only after a successful debit, so the finally path can retry a failed normal-path attempt.</comment>

<file context>
@@ -97,35 +97,47 @@ export async function runAgentWorkflow(input: RunAgentWorkflowInput): Promise<vo
+  let charged = false;
+  const chargeTurn = async () => {
+    if (charged) return;
+    charged = true;
+    const metadata = result?.responseMessage?.metadata as AgentMessageMetadata | undefined;
+    await handleChatCredits({
</file context>

@sweetmantech

Copy link
Copy Markdown
Contributor Author

Verification — preview + CI + unit

Preview: https://api-19v0lupdi-recoup.vercel.app — built from this PR's head commit 007840d1, Vercel status success, root returns HTTP 200.

CI on 007840d1 (all green): format ✅ · lint ✅ · test ✅ (full vitest suite) · Vercel ✅ · CodeRabbit ✅ · cubic ✅.

Verified (unit, RED→GREEN)

The two tests that codified the gap were flipped to assert the correct behavior, and fail on main's code before this change:

  • runAgentWorkflow.test.ts20/20 pass
  • app/lib/workflows + lib/credits129/129 pass
  • eslint on both changed files → clean
  • CI's test job re-runs all of this against the PR commit → pass.
Turn outcome Before After
Normal finish (responseMessage) 1 charge (real usage) 1 charge — unchanged
User-abort (responseMessage) 1 charge 1 charge — unchanged
Returns no responseMessage 0 charges 1 charge (1¢ floor + model_id row) ✅
Throws after send_email fired 0 charges 1 charge (1¢ floor + model_id row) ✅; error still propagates

Not verified by live preview curl — and why (being explicit)

This is an internal change to the runAgentWorkflow Vercel Workflow; no HTTP endpoint exercises the fixed branch. The fix only fires when a turn runs a customer-facing tool (send_email) and then throws / returns no responseMessage. That failure-after-side-effect can't be induced through a request to the preview URL (no fault-injection hook), and I'm deliberately not triggering live scheduled/chat runs to force it — those email real customers. So a preview curl isn't a meaningful check for this branch; the unit tests exercise the exact code path (mock runAgentStep to throw / return no message, assert handleChatCredits is now called once with the 1¢-floor args).

Observable acceptance (post-merge)

The bug already reproduced in prod: Brauxelion's Kimi-K3 briefing (account fade8fd2-…) emailed at 20:54 but wrote 0 usage_events rows with a model_id (vs the Sonnet-5 run's 1 @ 106¢). Done-when after merge: the next scheduled run that emails-then-fails writes a usage_events row with the real model_id and debits ≥1¢. I can watch usage_events for that account after deploy to confirm, or wire a prod canary with a forced post-send_email throw if a deterministic pre-merge check is wanted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant